package com.jinken._03part;

import com.jinken._03part.domain.Order;
import org.apache.rocketmq.client.exception.MQBrokerException;
import org.apache.rocketmq.client.exception.MQClientException;
import org.apache.rocketmq.client.producer.DefaultMQProducer;
import org.apache.rocketmq.client.producer.MessageQueueSelector;
import org.apache.rocketmq.client.producer.SendResult;
import org.apache.rocketmq.common.message.Message;
import org.apache.rocketmq.common.message.MessageQueue;
import org.apache.rocketmq.remoting.exception.RemotingException;

import java.util.ArrayList;
import java.util.List;

/**
 * 生产者
 */
public class Producer {
    public static void main(String[] args) throws MQClientException, MQBrokerException, RemotingException, InterruptedException {
        //创建生产者对象
        DefaultMQProducer dmp = new DefaultMQProducer("part_producer_group");
        //设置NamseServer地址
        dmp.setNamesrvAddr("192.168.126.100:9876");
        //启动生产者
        dmp.start();

        List<Order> orders = orderList();

        //循环消息数据
        for (Order order : orders) {

            //创建消息对象
            Message message = new Message("part_topic", "", order.toString().getBytes());

            //发送消息，并选择消息队列
            SendResult result = dmp.send(message, new MessageQueueSelector() {
                /**
                 * 队列选择
                 * @param list 队列集合
                 * @param message 消息
                 * @param o send方法的第三个参数
                 * @return
                 */
                @Override
                public MessageQueue select(List<MessageQueue> list, Message message, Object o) {
                    /**
                     * 让相同订单id的消息选择通一个队列
                     * orderId % list.size()
                     */
                    //根据订单id选择队列
                    int index = (int) ((Long)o % list.size());

                    return list.get(index);
                }
            },order.getOrderId());
            System.out.println("result = " + result);


        }


        //关闭生产者
        dmp.shutdown();
    }

    //生成很多订单方法
    public static List<Order> orderList(){

        List<Order> orders = new ArrayList<>();

        orders.add(new Order(3L,"创建订单"));
        orders.add(new Order(4L,"创建订单"));
        orders.add(new Order(1L,"创建订单"));
        orders.add(new Order(1L,"支付订单"));
        orders.add(new Order(4L,"支付订单"));
        orders.add(new Order(3L,"支付订单"));
        orders.add(new Order(2L,"创建订单"));
        orders.add(new Order(2L,"支付订单"));
        orders.add(new Order(3L,"订单完成"));
        orders.add(new Order(4L,"订单完成"));
        orders.add(new Order(1L,"订单完成"));
        orders.add(new Order(2L,"订单完成"));

        return orders;
    }


}
